<?php

namespace Yolo\Rpc\Annotations;

use Attribute;
use Yolo\Components\Cache\CacheInterface;
use Yolo\Components\Cache\MemoryCache;
use Yolo\Components\Cache\RedisCache;
use Yolo\Di\DI;

/**
 * Marks a property as a cache object.
 */
#[Attribute(Attribute::TARGET_PROPERTY)]
class Cache
{
    public function __construct(
        private readonly string $driver = 'default'
    ){
    }

    /**
     * Injects the cache object.
     * @throws \ReflectionException
     * @throws \Yolo\Di\Errors\CircularDependencyException
     * @throws \Yolo\Di\Errors\ParameterTypeEmptyException
     */
    public function inject(): CacheInterface
    {
        return match ($this->driver) {
            'memory' => DI::use(MemoryCache::class),
            default  => DI::use(RedisCache::class)
        };
    }

    public static function setDriver(string $driver): void
    {
        // 设置缓存驱动
        switch ($driver) {
            case 'redis':
                DI::bind(CacheInterface::class, RedisCache::class);
                break;

            default:
                DI::bind(CacheInterface::class, MemoryCache::class);
                break;
        }
    }
}
